package cn.longge.aspect;

import cn.longge.entity.SysLog;
import cn.longge.entity.SysRole;
import cn.longge.entity.SysUser;
import cn.longge.service.ISysLogService;
import cn.longge.utils.IPUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
public class LogAspect {

    @Autowired
    private ISysLogService sysLogService;

    @Autowired
    private HttpServletRequest request;

    @Pointcut("within(cn.longge.service..*Impl)")
    public void pointcut(){}

    @Before("pointcut()")
    public void before(){}

    @AfterReturning("pointcut()")
    public void afterReturnning(JoinPoint joinPoint){
        if(!"SysLogServiceImpl".equals(joinPoint.getTarget().getClass().getSimpleName())){
            SysLog sysLog = getSysLog(joinPoint,null);
            sysLogService.insertSelective(sysLog);
        }

    }

    @AfterThrowing(pointcut = "pointcut()",throwing = "e")
    public void afterThrowing(JoinPoint joinPoint,Exception e){
        if(!"SysLogServiceImpl".equals(joinPoint.getTarget().getClass().getSimpleName())){
            SysLog sysLog = getSysLog(joinPoint,e);
            sysLogService.insertSelective(sysLog);
        }
    }

    public SysLog getSysLog(JoinPoint joinPoint,Exception e){
        SysUser user = (SysUser) request.getSession().getAttribute("loginUser");
        SysLog sysLog = new SysLog();
        String requestURI = request.getRequestURI();
        sysLog.setRequestUri(requestURI);
        sysLog.setType(null != e ? "2" : "1");
        sysLog.setCreateBy(null != user ? user.getName() : null);
        sysLog.setCreateDate(new Date());
        sysLog.setRemoteAddr(IPUtils.getClientAddress(request));
        sysLog.setUserAgent(request.getHeader("User-Agent"));
        sysLog.setMethod(request.getMethod());
        sysLog.setException(null != e ? e.toString() : null);

        Object[] args = joinPoint.getArgs();
        if(null != args && 0 < args.length){
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < args.length; i++) {
                //[参数1，类型:SysArea，值:{"updateBy":"2,超级管理员","id":1,"parentId":0,"icon":"fa fa-institution","parentIds":"0,","oldParentIds":"0,","name":"中国","remarks":"","code":"100000","type":"1","updateDate":1425191153080}]
                if(null != args[i]){
                    sb.append("[参数").append(i + 1).append(",类型：").append(args[i].getClass().getSimpleName()).
                            append(",值：").append(args[i]).append("]");
                }
            }
            sysLog.setParams(sb.toString());
        }
        return sysLog;
    }
}
